package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * AxdrInteger64类
 * 实现64位整数数据的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class AxdrInteger64 implements AxdrType {
    private long value = 0;
    private byte[] dataCode = null;

    public AxdrInteger64() {
    }

    public AxdrInteger64(long value) {
        this.value = value;
    }

    public long getValue() {
        return value;
    }

    public void setValue(long value) {
        this.value = value;
    }

    public byte[] getDataCode() {
        return dataCode;
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        // 解码8个字节的整数（大端序）
        long b1 = input.read() & 0xFFL;
        long b2 = input.read() & 0xFFL;
        long b3 = input.read() & 0xFFL;
        long b4 = input.read() & 0xFFL;
        long b5 = input.read() & 0xFFL;
        long b6 = input.read() & 0xFFL;
        long b7 = input.read() & 0xFFL;
        long b8 = input.read() & 0xFFL;
        this.value = (b1 << 56) | (b2 << 48) | (b3 << 40) | (b4 << 32) | (b5 << 24) | (b6 << 16) | (b7 << 8) | b8;
        return 8;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        // 编码8个字节的整数（大端序）
        try {
            output.write((int) ((this.value >> 56) & 0xFF));
            output.write((int) ((this.value >> 48) & 0xFF));
            output.write((int) ((this.value >> 40) & 0xFF));
            output.write((int) ((this.value >> 32) & 0xFF));
            output.write((int) ((this.value >> 24) & 0xFF));
            output.write((int) ((this.value >> 16) & 0xFF));
            output.write((int) ((this.value >> 8) & 0xFF));
            output.write((int) (this.value & 0xFF));
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
        return 8;
    }

    /**
     * 编码并保存
     * 
     * @param encodingSizeGuess 编码大小预估
     */
    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    @Override
    public String toString() {
        return String.valueOf(this.value);
    }
}